using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Authorization.Users;
using Abp.Domain.Repositories;
using Yozeev.UserManagerment.Users;

namespace Yozeev.SystemConfig.DomainService
{
	/// <summary>
	/// Power领域层的业务管理
	///</summary>
	public class PowerManager :YozeevDomainServiceBase, IPowerManager
    {
		private readonly IRepository<Power,Guid> _repository;

		private readonly IRepository<PowerRole, Guid> _powerRole;

		private readonly IRepository<UserRole, long> _userRole;

		/// <summary>
		/// Power的构造方法
		///</summary>
		public PowerManager(IRepository<Power, Guid> repository,
			IRepository<PowerRole, Guid> powerRole,
			IRepository<UserRole, long> userRole)
		{
			_powerRole = powerRole;
			_userRole = userRole;
			_repository =  repository;
		}

		/// <summary>
		/// 根据用户id查询角色权限
		/// </summary>
		/// <param name="userId">用户id</param>
		/// <returns></returns>
		public List<Power> GetPowerByUserId(long userId)
		{
			var roleIds = _userRole.GetAll()
				.Where(u => userId.Equals(u.UserId))
				.Select(u => u.RoleId)
				.ToList();
			var powerIds = _powerRole.GetAll()
				.Where(p => roleIds.Contains(p.RoleId))
				.Select(p => p.PowerId)
				.ToList();
			var powers = _repository.GetAll().Where(p => powerIds.Contains(p.Id));
			return powers.ToList();
		}

		#region 根据角色ID和权限代码查询是否有对应的权限功能
		/// <summary>
		/// 根据角色ID和权限代码查询是否有对应的权限功能
		/// </summary>
		/// <param name="userId">用户id</param>
		/// <returns></returns>
		public PowerRole GetIsPowerInfo(int roleid=0,string powercode="")
		{
			var powers = _repository.GetAll()
				.Where(p => p.PowerCode == powercode)
				.FirstOrDefault();

			var powerrole = _powerRole.GetAll()
				.Where(p => p.RoleId == roleid && p.PowerId == powers.Id)
				.FirstOrDefault();

			return powerrole;
		}
		#endregion


		/// <summary>
		/// 初始化
		///</summary>
		public void InitPower()
		{
			throw new NotImplementedException();
		}
	}
}
